<template>
  <yy-paging
    v-model="dataList"
    @query="queryList"
    ref="paging"
    :auto="true"
    @scroll="scroll"
    :refresher-enabled="false"
    useVirtualList
    :loadingMoreEnabled="false"
  >
    <template #empty>
      <yy-empty text="暂无相关鱼种"></yy-empty>
    </template>
    <template #loadingMoreNoMore>
      <yy-nomore></yy-nomore>
    </template>
    <template #top>
      <!-- <u-navbar
        back-text=""
        :is-back="true"
        :customBack="complete"
        :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
        :border-bottom="false"
        :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
      >
        <view class="flex flex-1 gap-4 items-center px-4">
          <u-search
            :placeholder="search.placeholder"
            v-model="search.keyword"
            bg-color="#fff"
            :focus="search.focus"
            @search="searchFor"
            @custom="searchFor"
            @change="searchFor"
            @clear="clear"
            :showAction="false"
          ></u-search>
          <view @click="complete">完成</view>
        </view>
      </u-navbar> -->

      <u-navbar
        :is-back="false"
        :background="{ backgroundColor: isScroll ? '#F2F5F7' : 'transparent' }"
        :border-bottom="false"
        :custom-style="{ transition: 'background-color 0.3s ease-in-out' }"
      >
        <view class="flex gap-2 items-center px-3 w-full">
          <view class="flex col-span-1 items-center" @click="vk.navigateBack()">
            <image src="/static/dddr128.png" mode="aspectFill" class="size-6" />
          </view>
          <view class="line-clamp-1 flex flex-1 col-span-1 justify-center">
            <u-search
              :placeholder="search.placeholder"
              v-model="search.keyword"
              bg-color="#fff"
              :focus="search.focus"
              @search="searchFor"
              @custom="searchFor"
              @change="searchFor"
              @clear="clear"
              :showAction="false"
            ></u-search>
          </view>
          <view class="flex col-span-1 justify-end">
            <view @click="complete" class="text-[.875rem]">完成</view>
          </view>
        </view>
      </u-navbar>
      <view class="flex flex-col gap-3 p-4">
        <view class="flex gap-1 items-center" v-if="selectedFish.length">
          <view class="text-[.875rem] text-[#161A24]"> 已选鱼种</view>
          <view class="text-[.75rem] text-[#8E9299]">({{ selectedFish.length }}/{{ maxSelectCount }})</view>
        </view>
        <view class="flex flex-wrap gap-2" v-if="selectedFish.length">
          <view v-for="(i, k) in selectedFish" class="flex gap-1 items-center px-4 py-2 bg-white rounded-full" :key="k">
            <view class="text-[.75rem] text-[#161A24]"
              >{{ i.name }}
              <text v-if="i.alias"> ({{ i.alias }}) </text>
            </view>
            <image src="/static/dddr24.png" @click="deleteSelected(i)" mode="aspectFill" class="size-4" />
          </view>
        </view>
        <!-- <view class="text-[.875rem] text-[#161A24]"> 全部鱼种</view> -->
      </view>
    </template>
    <template #cell="{ item }">
      <view class="px-4">
        <view
          class="bg-[#FFFFFF] rounded-[.75rem] flex justify-between items-center p-4 mb-3"
          @click="toggleSelect(item)"
        >
          <view class="flex gap-4 items-center">
            <view
              class="w-[4.25rem] h-[2.5rem] rounded-[.25rem] overflow-hidden"
              @click.stop="previewImage(item.thumb)"
            >
              <u-image
                :src="vk.myfn.handleImageUrl(item.thumb)"
                class="!size-full"
                mode="aspectFill"
                :lazy-load="true"
              />
            </view>
            <view class="text-[.875rem] text-[#161A24]">
              {{ item.name }}
              <text v-if="item.alias"> ({{ item.alias }}) </text>
            </view>
          </view>
          <view
            class="size-5 flex justify-center items-center place-content-center rounded-full transition-all duration-300"
            :class="selectedFishMap[item.id] ? 'bg-[#00BFBF] border-[#00BFBF]' : 'bg-[#FFFFFF] border'"
          >
            <u-icon name="checkmark" color="#FFFFFF" size="20" v-if="selectedFishMap[item.id]"></u-icon>
          </view>
        </view>
      </view>
    </template>
  </yy-paging>
</template>

<script>
  export default {
    data() {
      return {
        isScroll: false, // 是否滚动
        dataList: [], // 数据列表
        automatic: false, // 是否自动加载
        search: {
          placeholder: '搜索鱼名', // 搜索框占位符
          keyword: '', // 搜索关键词
          focus: true // 是否获取焦点
        },
        selectedFish: [], // 已选中的鱼种
        selectedFishMap: {}, // 已选中鱼种的映射表，用于快速查找
        maxSelectCount: 5, // 最大可选数量
        basan_type: '' // 鱼种类型
      }
    },
    onLoad(options) {
      this.basan_type = options.basan_type
      const eventChannel = this.getOpenerEventChannel()
      // 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
      if (eventChannel.on) {
        eventChannel.on('data', data => {
          this.selectedFish = data
        })
      }
    },
    watch: {
      // 监听selectedFish变化，更新映射表
      selectedFish: {
        handler(newVal) {
          this.selectedFishMap = {}
          newVal.forEach(fish => {
            this.selectedFishMap[fish.id] = true
          })
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      change(e) {
        console.log('e==> ', e)
        if (!e) {
          this.$refs.paging.reload()
        }
      },
      complete() {
        const eventChannel = this.getOpenerEventChannel()
        if (eventChannel.emit) eventChannel.emit('update', this.selectedFish)
        vk.navigateBack()
      },
      deleteSelected(i) {
        // 从已选中的鱼种列表中删除指定索引的鱼种
        const index = this.selectedFish.findIndex(fish => fish.id === i.id)
        if (index > -1) {
          this.selectedFish.splice(index, 1)
        }
      },
      clear() {
        this.$refs.paging.reload()
      },
      searchFor(e) {
        if (!this.search.keyword) return this.$refs.paging.reload()
        console.log('this.search.keyword==> ', this.search.keyword)
        this.dataList = this.d.filter(item => {
          const keyword = this.search.keyword.toLowerCase()
          const fishName = item.name.toLowerCase()
          const fishAlias = item.alias.toLowerCase()
          return fishName.includes(keyword) || fishAlias.includes(keyword)
        })
        // this.dataList = [
        //   {
        //     first: 'A',
        //     id: 1,
        //     name: '埃及塘鲺',
        //     thumb: '/fish/20240228154534077FF.jpg',
        //     type: 'fish_species',
        //     user_id: 0,
        //     zp_index: 0,
        //     zp_unique_index: '295157ed901754288281007-0'
        //   }
        // ]

        // if (!e) return this.$refs.paging.reload()

        // // 根据搜索关键词筛选数据列表
        // this.dataList = this.dataList.filter(item => {
        //   const searchValue = e.toLowerCase()
        //   const fishName = item.name.toLowerCase()
        //   return fishName.includes(searchValue)
        // })
        // console.log(' this.dataList==> ', this.dataList)
      },

      // 监听滚动
      scroll(e) {
        this.isScroll = e.detail.scrollTop > 0
      },

      // 加载数据
      async queryList(page, limit) {
        let obj = {
          basan_type: this.basan_type,
          page,
          limit
        }
        let res = await api.getFishOptions(obj)
        // console.log('res.data.fish_species==> ', res.data.fish_species)
        this.d = res.data.fish_species
        this.$refs.paging.complete([])
        // this.$refs.paging.complete(res.data.fish_species)
        // console.log('this.dataList==> ', this.dataList)
      },
      toggleSelect(item) {
        if (this.selectedFishMap[item.id]) {
          // 已选中，取消选择
          const index = this.selectedFish.findIndex(fish => fish.id === item.id)
          if (index > -1) {
            this.selectedFish.splice(index, 1)
            delete this.selectedFishMap[item.id] // 使用JavaScript的delete操作符
          }
        } else {
          // 未选中，添加到选中列表
          if (this.selectedFish.length >= this.maxSelectCount) {
            uni.showToast({
              title: `最多只能选择${this.maxSelectCount}种鱼`,
              icon: 'none'
            })
            return
          }
          this.selectedFish.push(item)
          this.$set(this.selectedFishMap, item.id, true) // 直接添加到映射表
        }
      },

      // 判断是否已选中
      isSelected(item) {
        return this.selectedFish.some(fish => fish.id === item.id)
      }
    }
  }
</script>

<style lang="scss" scoped></style>
